package com.example.exceldemo.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.util.concurrent.*;

/**
 * 异步任务管理器
 */
@Slf4j
@Component
public class AsyncTaskManager {
    
    private final ExecutorService taskExecutor;
    
    public AsyncTaskManager() {
        // 创建线程池
        taskExecutor = new ThreadPoolExecutor(
                5, // 核心线程数
                10, // 最大线程数
                60, // 空闲线程存活时间
                TimeUnit.SECONDS, // 时间单位
                new LinkedBlockingQueue<>(100), // 队列
                r -> {
                    Thread thread = new Thread(r);
                    thread.setName("doc-generation-thread-" + thread.getId());
                    return thread;
                }, // 线程工厂
                new ThreadPoolExecutor.AbortPolicy() // 拒绝策略
        );
    }
    
    /**
     * 提交任务
     *
     * @param task 任务
     * @return Future对象
     */
    public <T> Future<T> submit(Callable<T> task) {
        return taskExecutor.submit(task);
    }
    
    /**
     * 执行任务
     *
     * @param task 任务
     */
    public void execute(Runnable task) {
        taskExecutor.execute(task);
    }
    
    /**
     * 应用关闭时关闭线程池
     */
    @PreDestroy
    public void shutdown() {
        log.info("正在关闭文档生成线程池...");
        taskExecutor.shutdown();
        try {
            if (!taskExecutor.awaitTermination(60, TimeUnit.SECONDS)) {
                log.warn("线程池未在60秒内完全终止，强制关闭");
                taskExecutor.shutdownNow();
            }
        } catch (InterruptedException e) {
            log.error("等待线程池关闭时被中断", e);
            Thread.currentThread().interrupt();
        }
        log.info("文档生成线程池已关闭");
    }
} 